<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\ShopModel;
use App\Model\UsersLineUpModel;
use App\Model\UsersModel;
use App\Services\Cache;
use App\Services\ChatServices;
use App\Services\WechatServices;
use Carbon\Carbon;
use EasyWeChat\Kernel\Exceptions\HttpException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\Kernel\Exceptions\RuntimeException;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Psr\SimpleCache\InvalidArgumentException;

class UsersDao extends BaseDao
{

    public static function get_user_builder($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = UsersModel::query();
        $query->when(checkIsHasField($params,'search_key'),function ( $query)use ($params){
            $query->whereRaw('(user_phone Like "%'.$params['search_key'].'%" OR nickname Like "%'.$params['search_key'].'%" OR spread_id Like "%'.$params['search_key'].'%")');
        });
        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'user_phone'),function ($query)use ($params){
            $query->where('user_phone',$params['user_phone']);
        });


        $query->when(checkIsHasField($params,'spread_id'),function ($query)use ($params){
            $query->where('spread_id',$params['spread_id']);
        });

        $query->when(checkIsHasField($params,'share_code'),function ($query)use ($params){
            $query->where('share_code',$params['share_code']);
        });

        $query->when(checkIsHasField($params,'vip_index'),function ($query)use ($params){
            $query->where('vip_index',$params['vip_index']);
        });


        $query->when(checkIsHasField($params,'vip_level'),function ($query)use ($params){
            $query->where('vip_level',$params['vip_level']);
        });

        $query->when(checkIsHasField($params,'openid'),function ($query)use ($params){
            $query->where('openid',$params['openid']);
        });



        return $query;
    }


    /**
     * @param array $params
     * @return array
     * @throws InvalidArgumentException
     * @throws SysExceptions
     * @throws HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws InvalidConfigException
     * @throws RuntimeException
     */
    public static function login(array $params = []): array
    {
        $result = WechatServices::wechat_login($params['code'],$params['iv'],$params['encryptedData'],$params['code2']);
        $userBuilder = self::get_user_builder([
            'openid'=>$result['openid']
        ]);
        if(!$userBuilder->exists()){
            $insertValue = [
                'nickname'=>'新用户',
                'openid'=>$result['openid'],
                'user_phone'=>$result['phone']
            ];
            if(checkIsHasField($params,'spread_id')){
                $insertValue['spread_id'] = $params['spread_id'];
            }
            if(self::get_user_builder()->create($insertValue) === false){
                self::error('登陆失败');
            }
        }else{
            $info = $userBuilder->first()->toArray();
            $update = [
                'openid'=>$result['openid']
            ];
            if($userBuilder->update($update) === false){
                self::error('登陆更新失败');
            }
        }
        return $userBuilder->first()->toArray();
    }

    public static function getUserInfo(array $array): array
    {
        if(!Cache::hasCache('KEU_FU1')){
            Cache::setCache('KEU_FU1',SettingsDao::get_settings_builder_query([
                'share_bg'=>'share_bg'
            ])->value('key_text'),Carbon::now()->addMinutes(15));
        }
        $info =  self::get_user_builder($array)->with('shopInfo')->first()->toArray();
        $info['jinri'] = BillDao::get_bill_builder([
            'start_time'=>strtotime(date('Y-m-d')),
            'user_id'=>$info['user_id'],
            'status'=>1
        ])->where('type',1)->where('pm',1)->sum('num');
        $info['tixian'] = BillDao::get_bill_builder([
            'user_id'=>$info['user_id'],
            'status'=>1
        ])->where('type',3)->where('pm',0)->sum('num');
        $info['kefu_url'] = Cache::getCacheValue('KEU_FU1');
        return  $info;
    }

    public static function get_user_page(array $all)
    {
        return self::get_user_builder($all)->with('spreadInfo')->paginate();
    }

    /**
     * @throws SysExceptions
     */
    public static function set_shop_user(array $params)
    {
        $shop_query = self::get_shop_builder([
            'user_id'=>$params['user_id']
        ]);
        if($shop_query->exists()){
            $result = $shop_query->update(self::filterFields($params,new ShopModel()));
        }else{
            $result = $shop_query->create($params);
        }
        if($result === false){
            self::error('设置失败');
        }
    }



    public static function get_shop_builder($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $shop_query = ShopModel::query();

        $shop_query->when(checkIsHasField($params,'shop_id'),function ($query)use ($params){
            $query->where('shop_id',$params['shop_id']);
        });


        $shop_query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $shop_query->when(checkIsHasField($params,'area_id'),function ($query)use ($params){
            $query->where('area_id',$params['area_id']);
        });



        return $shop_query;
    }

    public static function set_json_city_address(array $params)
    {
        return self::get_user_builder([
            'user_id'=>$params['user_id']
        ])->update([
            'json_city_address'=>json_encode([
//                'city_id'=>$params['city_id'],
//                'province_id'=>$params['province_id'],
//                'area_id'=>$params['area_id'],
                'address'=>$params['address'],
                'phone'=>$params['phone'],
                'real_name'=>$params['real_name']
            ])
        ]);
    }

    public static function set_card_json(array $array_merge)
    {
        if(!checkIsHasField($array_merge,'card_no')){
            self::error('请输入银行卡号');
        }else if(!checkIsHasField($array_merge,'card_name')){
            self::error('请输入银行名称');
        }else if (!checkIsHasField($array_merge,'name')){
            self::error('请输入您的姓名');
        }
        if(self::get_user_builder([
                'user_id'=>$array_merge['user_id']
            ])->update([
                'bank_card_json'=>json_encode([
                    'card_no'=>$array_merge['card_no'],
                    'card_name'=>$array_merge['card_name'],
                    'name'=>$array_merge['name'],
                ],JSON_UNESCAPED_UNICODE)
            ]) === false){
            self::error('设置失败');
        }
    }


    public static function widthwal(array $params = []){
        $userInfo = self::get_user_builder([
            'user_id'=>$params['user_id']
        ])->first();
        if($params['money'] < 50){
            self::error('提现金额不能小于50');
        }
        if($userInfo['money'] < $params['money']){
            self::error('用户数量不足');
        }
        if(BillDao::get_bill_builder([
            'user_id'=>$params['user_id'],
            'status'=>0
        ])->exists()){
            self::error('当前有正在审核的提现');
        }

        DB::beginTransaction();
        $res = BillDao::get_bill_builder()->create([
            'user_id'=>$params['user_id'],
            'num'=>$params['money'],
            'pm'=>0,
            'type'=>3,
            'title'=>'用户进行提现',
            'json_data'=>json_encode($userInfo['bank_card_json']),
            'status'=>0
        ]);
        $res !== false && $res = self::get_user_builder([
            'user_id'=>$params['user_id']
        ])->decrement('money',$params['money']);
        if( $res=== false){
            DB::rollBack();
            self::error('提现失败');
        }
        DB::commit();
    }

    public static function set_hehuo(array $all)
    {
        $user_info = self::get_user_builder([
            'user_id'=>$all['user_id']
        ])->first()->toArray();
        $is_huo = 1;
        if($user_info['is_hehuo'] == 1){
            $is_huo = 0;
        }
        if(self::get_user_builder([
            'user_id'=>$all['user_id']
        ])->update([
            'is_hehuo'=>$is_huo
        ]) === false){
            self::error('设置失败');
        }
    }


    public static function update_nickname_headimgurl(array $params)
    {
        DB::beginTransaction();
        $user_id= self::deleteParamId($params,'user_id');
        if(self::get_user_builder([
                'user_id'=>$user_id
            ])->update(self::filterFields($params,new UsersModel())) === false){
            DB::rollBack();
            self::error('修改失败');
        }
        DB::commit();
    }

    public static function get_shop_page(array $all): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return self::get_shop_builder($all)->with('userInfo')->paginate();
    }

    public static function moneyChongzhi(array $params)
    {
        DB::beginTransaction();
        try {
            $res = BillDao::get_bill_builder()->create([
                'user_id'=>$params['user_id'],
                'num'=>$params['money'],
                'pm'=>1,
                'type'=>3,
                'title'=>'后台充值',
                'status'=>1
            ]);
            $res !== false && $res = self::get_user_builder([
                'user_id'=>$params['user_id']
            ])->increment('money',$params['money']);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error('充值失败');
        }
    }

    public static function get_now_money_prices()
    {
        return UsersLineUpModel::query()->with('userInfo')->whereRaw('(money_now_price < money)')->get();
    }
}
